package com.suncmf.demo.core;



import org.springframework.beans.factory.annotation.Autowired;


import java.lang.reflect.Method;

/**
 * 基于通用mybatis.spring.boot的Service接口的实现
 */
public abstract class AbstractService<T extends Object> implements Service<T> {

    @Autowired
    protected MyMapper<T> mapper;

    @Override
    public int save(T record) {
        try{
            Class clazz =  record.getClass();
            Method method = clazz.getMethod("getId", null);
            Object id =  method.invoke(record);
            if (id == null) { //没有主键id,就是插入
                mapper.insertSelective(record);
            }else { //更新操作
                 mapper.updateByPrimaryKeySelective(record);
            }
            return (int) method.invoke(record);
        }catch (Exception e){
            return 0;
        }
    }

    @Override
    public int forceDeleteById(Integer id) {
        return mapper.deleteByPrimaryKey(id);
    }

    public T findById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

}
